package phonebook;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.andro.chansung.ConstantName;
import com.andro.chansung.ConstantURL;
import com.andro.chansung.DB;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class PhoneUpdateThread extends Thread {
	private Activity activity;
	private Handler handler;
	private String url;
	
	public PhoneUpdateThread(Activity activity, Handler handler, String url) {
		this.activity = activity;
		this.handler = handler;
		this.url = url;
	}
	
	public void run() {
		try {
			Document doc = Jsoup.connect(url).get();
			
			Elements outerPartyTags = doc.select("outer_party");
			SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			
			for( Element element : outerPartyTags ) {
				DB.insertDataIntoPhoneOuter(db, element.text());
			}
			
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		/*
		try {
			Document doc = Jsoup.connect(url).get();
			Elements outerPartyTags = doc.select("outer_party");
			
			for( Element element : outerPartyTags ) {
				String headName = element.attr("name");
				Elements innerPartyTags = element.select("inner_party");
				
				for( Element innerElement : innerPartyTags ) {
					String title = innerElement.select("name").get(0).text();
					
					Map<String, String> phoneMap = new HashMap<String, String>();
					if( !innerElement.select("phone").isEmpty() ) {
						String phoneNumber = innerElement.select("phone").get(0).text();						
						if( phoneNumber.contains("-") ) {
							phoneMap.put(title, phoneNumber.split("\n")[0].split(",")[0].split("~")[0]);	
						} else {
							phoneMap.put(title, "055-320-" +  phoneNumber.split("\n")[0].split(",")[0].split("~")[0]);	
						}
					}
					
					Map<String, String> faxMap = new HashMap<String, String>();
					if( !innerElement.select("fax").isEmpty() ) {
						String faxNumber = innerElement.select("fax").get(0).text();
						faxMap.put(title, faxNumber.split("\n")[0].split(",")[0].split("~")[0]);
					}
					
					writeData(new Phone(headName, phoneMap, faxMap));
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		*/
		handler.sendEmptyMessage(0);
	}
	
	private void writeData(Phone phone) {
		SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
		DB.insertDataIntoPhoneBookTable(db, phone);
		db.close();	
	}
}
